package de.slothsoft.commons.swing;

import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;


public abstract class AbstractDataBindingPanel<T> extends JPanel {

    private static final long serialVersionUID = 1L;

    private DataBinding<T> dataBinding;
    private T model;

    public AbstractDataBindingPanel(T model) {
	this.model = model;
	createControls(this);
    }

    protected final void createControls(JPanel mainPanel) {
	this.dataBinding = new DataBinding<>(this.model);
	createControls(mainPanel, this.dataBinding);
	this.dataBinding.updateTargets();
    }

    protected abstract void createControls(JPanel mainPanel, DataBinding<T> dataBinding);

    public DataBinding<T> getDataBinding() {
	return this.dataBinding;
    }

    public T getModel() {
	return this.model;
    }

    protected JTextField createText(JComponent component, String property, int x, int y) {
	JTextField textField = createText(component, x, y);
	this.dataBinding.bind(textField, this.model, property);
	return textField;
    }

    protected static JTextField createText(JComponent component, int x, int y) {
	JTextField textField = new JTextField();
	component.add(textField, GridBagUtil.textFieldDefaults(x, y));
	return textField;
    }

    protected JTextField createPassword(JComponent component, String property, int x, int y) {
	JTextField textField = createPassword(component, x, y);
	this.dataBinding.bind(textField, this.model, property);
	return textField;
    }

    protected static JTextField createPassword(JComponent component, int x, int y) {
	JPasswordField textField = new JPasswordField();
	component.add(textField, GridBagUtil.textFieldDefaults(x, y));
	return textField;
    }

    protected JCheckBox createCheckBox(JComponent component, String property, int x, int y) {
	JCheckBox check = createCheckBox(component, x, y);
	this.dataBinding.bind(check, this.model, property);
	return check;
    }

    protected static JCheckBox createCheckBox(JComponent component, int x, int y) {
	JCheckBox checkBox = new JCheckBox();
	component.add(checkBox, GridBagUtil.textFieldDefaults(x, y));
	return checkBox;
    }
}
